package com.pybox.spec;

import com.pybox.entity.TSession;
import com.pybox.entity.TVersion;
import com.pybox.util.UserUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 描述：TSession Specification
* @author wuyingkai
* @date 2018-09-15
*/


public class TVersionSpec implements Specification<TVersion> {

    private Map<String, String> params;

    public TVersionSpec(Map<String, String> params){
        this.params = params;
    }

    @Override
    public Predicate toPredicate(Root<TVersion> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        String hdVersion = this.params.get("hdVersion");
        String swVersion = this.params.get("swVersion");
        String fpVersion = this.params.get("fpVersion");
        String customerId = UserUtils.getCustomerId().toString();
        List<Predicate> ps = new ArrayList<>();

        if (!StringUtils.isEmpty(customerId)) {
            ps.add(criteriaBuilder.equal(root.get("customerId"), customerId));
        }
        if (!StringUtils.isEmpty(hdVersion)) {
            ps.add(criteriaBuilder.like(root.get("hdVersion"), "%" + hdVersion + "%"));
        }
        if (!StringUtils.isEmpty(swVersion)) {
            ps.add(criteriaBuilder.like(root.get("swVersion"), "%" + swVersion + "%"));
        }
        if (!StringUtils.isEmpty(fpVersion)) {
            ps.add(criteriaBuilder.like(root.get("fpVersion"), "%" + fpVersion + "%"));
        }

        criteriaQuery = criteriaQuery.where(ps.toArray(new Predicate[ps.size()]));

        return criteriaQuery.getRestriction();
    }

}